package LC;

/**
 * https://leetcode.com/problems/sudoku-solver/description/
 * Write a program to solve a Sudoku puzzle by filling the empty cells.
 * Empty cells are indicated by the character '.'.
 * You may assume that there will be only one unique solution.
 */
public class LC_037_SudoKuSolver_Math {
    public static void main(String[] args) {

    }

    static class Solution {
        public static void solveSudoku(char[][] board) {
            if (board == null || board.length == 0) return;
            solve(board);
        }

        private static boolean solve(char[][] board) {
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if (board[i][j] == '.') {
                        for (char c = '1'; c <= '9'; c++) {
                            if (isValid(board, i, j, c)) {
                                board[i][j] = c;
                                if (solve(board)) return true;
                                else board[i][j] = '.';
                            }
                        }
                        return false;
                    }
                }
            }
            return true;
        }

        private static boolean isValid(char[][] board, int row, int col, char c) {
            for (int i = 0; i < board.length; i++) {
                if (board[i][col] == c || board[row][i] == c) return false;
                if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false;
            }
            return true;
        }
    }
}
